<template>
  <div v-loading="loading">
    <div class="margin-left relative" v-if="showHead">
      <div class="headDiv">
        <span style="font-size: 14px" class="text-bold margin-right-sm"
          >应收总计：{{ headtotalCost }}</span
        >
        <span class="margin-right-sm">余额：{{ headtotalRemain }}</span>
        <span>合计：{{ headAppend }}</span>
      </div>
    </div>

    <div class="margin-left relative" v-if="showHistory">
      <div class="headDiv">
        <span style="font-size: 14px" class="margin-right-sm">{{
          titleName
        }}</span>
        <span style="font-size: 14px" class="text-bold margin-right-sm"
          >应收总计：{{ headtotalCost }}</span
        >
        <span>余额：{{ headtotalRemain }}</span>
        <span>合计：{{ headAppend }}</span>
      </div>
    </div>
    <el-row>
      <el-col :sm="smWidth" :md="mdWidth" :lg="lgWidth">
        <el-card>
          <el-form :model="criteriaForm" ref="basisForm" size="mini">
            <el-row>
              <el-col :span="10">
                <el-form-item
                  label="应收客户"
                  label-width="70px"
                  prop="customerId"
                >
                  <template>
                    <el-select
                      v-if="!cus"
                      style="width: 70%"
                      v-model="criteriaForm.customerId"
                      filterable
                      remote
                      :disabled="disCus"
                      reserve-keyword
                      :remote-method="getCustomerMap"
                      placeholder="请输入客户名称"
                    >
                      <el-option
                        v-for="(item, value) in customerRemoteSource"
                        :key="value"
                        :label="item"
                        :value="parseInt(value)"
                      >
                      </el-option>
                    </el-select>
                    <el-select
                      v-else
                      style="width: 70%"
                      v-model="criteriaForm.customerId"
                      filterable
                      remote
                      :disabled="disCus"
                      reserve-keyword
                      placeholder="请输入客户名称"
                    >
                      <el-option
                        v-for="(item, value) in customerSource"
                        :key="value"
                        :label="item"
                        :value="parseInt(value)"
                      >
                      </el-option>
                    </el-select>
                    <el-checkbox v-model="criteriaForm.relatedSon"
                      >关联子公司</el-checkbox
                    >
                  </template>
                </el-form-item>
                <el-form-item
                  label="费用时间"
                  label-width="70px"
                  prop="endAccountDate"
                >
                  <el-date-picker
                    placeholder="开始时间"
                    suffix-icon="el-icon-date"
                    v-model="criteriaForm.startAccountDate"
                    value-format="yyyy-MM-dd"
                    style="width: 160px"
                  ></el-date-picker
                  >&nbsp;&nbsp;-&nbsp;&nbsp;
                  <el-date-picker
                    placeholder="结束时间"
                    suffix-icon="el-icon-date"
                    value-format="yyyy-MM-dd"
                    v-model="criteriaForm.endAccountDate"
                    style="width: 160px"
                  ></el-date-picker>
                </el-form-item>
                <div class="minheight" :class="{ maxheight: flag }">
                  <el-form-item
                    label="到港时间"
                    label-width="70px"
                    prop="endArrivalPortDate"
                  >
                    <el-date-picker
                      placeholder="开始时间"
                      suffix-icon="el-icon-date"
                      v-model="criteriaForm.startArrivalPortDate"
                      style="width: 160px"
                      value-format="yyyy-MM-dd"
                    ></el-date-picker
                    >&nbsp;&nbsp;-&nbsp;&nbsp;
                    <el-date-picker
                      placeholder="结束时间"
                      suffix-icon="el-icon-date"
                      v-model="criteriaForm.endArrivalPortDate"
                      style="width: 160px"
                      value-format="yyyy-MM-dd"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item
                    label="离港时间"
                    label-width="70px"
                    prop="endLeavePortDate"
                  >
                    <el-date-picker
                      placeholder="开始时间"
                      suffix-icon="el-icon-date"
                      v-model="criteriaForm.startLeavePortDate"
                      style="width: 160px"
                      value-format="yyyy-MM-dd"
                    ></el-date-picker
                    >&nbsp;&nbsp;-&nbsp;&nbsp;
                    <el-date-picker
                      placeholder="结束时间"
                      suffix-icon="el-icon-date"
                      v-model="criteriaForm.endLeavePortDate"
                      style="width: 160px"
                      value-format="yyyy-MM-dd"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item
                    label="签收时间"
                    label-width="70px"
                    prop="endSigneDate"
                  >
                    <el-date-picker
                      placeholder="开始时间"
                      suffix-icon="el-icon-date"
                      v-model="criteriaForm.startSigneDate"
                      style="width: 160px"
                      value-format="yyyy-MM-dd"
                    ></el-date-picker
                    >&nbsp;&nbsp;-&nbsp;&nbsp;
                    <el-date-picker
                      placeholder="结束时间"
                      suffix-icon="el-icon-date"
                      v-model="criteriaForm.endSigneDate"
                      style="width: 160px"
                      value-format="yyyy-MM-dd"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item
                    label="入库时间"
                    label-width="70px"
                    prop="endInstockDate"
                  >
                    <el-date-picker
                      placeholder="开始时间"
                      suffix-icon="el-icon-date"
                      v-model="criteriaForm.startInstockDate"
                      style="width: 160px"
                      value-format="yyyy-MM-dd"
                    ></el-date-picker
                    >&nbsp;&nbsp;-&nbsp;&nbsp;
                    <el-date-picker
                      placeholder="结束时间"
                      suffix-icon="el-icon-date"
                      v-model="criteriaForm.endInstockDate"
                      style="width: 160px"
                      value-format="yyyy-MM-dd"
                    ></el-date-picker>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="运单号"
                  label-width="70px"
                  prop="waybillNoTextArea"
                >
                  <el-input
                    size="large"
                    v-model="criteriaForm.waybillNoTextArea"
                    type="textarea"
                    name="waybillName"
                  ></el-input>
                </el-form-item>
                <div class="minheight" :class="{ maxheight: flag }">
                  <el-form-item
                    label="参考号"
                    label-width="70px"
                    prop="referenceNoTextArea"
                  >
                    <el-input
                      size="large"
                      v-model="criteriaForm.referenceNoTextArea"
                      type="textarea"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    label="物流方法"
                    label-width="70px"
                    prop="shippingWays"
                  >
                    <el-select
                      size="mini"
                      v-model="criteriaForm.shippingWays"
                      multiple
                    >
                      <el-option
                        v-for="(item, value) in shippingWaySource"
                        :key="value"
                        :label="item"
                        :value="value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="起运地"
                    label-width="70px"
                    prop="shippingWays"
                  >
                    <el-select
                      size="mini"
                      v-model="criteriaForm.shippingAddress"
                      multiple
                    >
                      <el-option
                        v-for="(item, value) in shippingAddressSource"
                        :key="value"
                        :label="item"
                        :value="value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="费用类型" prop="costType">
                    <el-select v-model="criteriaForm.costType">
                      <el-option label="FBA费用" value="0"></el-option>
                      <el-option label="海外仓费用" value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="国家："
                  label-width="70px"
                  prop="countryId"
                >
                  <el-select
                    size="mini"
                    v-model="criteriaForm.countryId"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="(v, i) in countrySource"
                      :key="i"
                      :label="v"
                      :value="i"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="币种：" label-width="70px" prop="currency">
                  <el-select
                    v-model="criteriaForm.currency"
                    multiple
                    size="mini"
                  >
                    <el-option
                      v-for="(item, value) in currencySource"
                      :key="value"
                      :label="item"
                      :value="value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <div class="minheight" :class="{ maxheight: flag }">
                  <el-form-item
                    label="追踪号"
                    label-width="70px"
                    prop="trackNumbers"
                  >
                    <el-input
                      size="large"
                      v-model="criteriaForm.trackNumbersTextArea"
                      type="textarea"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    label="费用名称"
                    label-width="70px"
                    prop="costName"
                  >
                    <el-select
                      size="mini"
                      multiple
                      filterable
                      clearable
                      v-model="criteriaForm.costName"
                    >
                      <el-option
                        v-for="(item, value) in costNameSource"
                        :key="value"
                        :label="item"
                        :value="parseInt(value)"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="2">
                <el-button
                  size="mini"
                  type="primary"
                  @click="query"
                  style="margin-left: 10px"
                  >查询</el-button
                >
                <el-button size="mini" style="margin-top: 20px" @click="reset"
                  >重置</el-button
                >
              </el-col>
            </el-row>
            <el-row style="text-align: center">
              <el-link
                :underline="false"
                @click="changeData"
                type="primary"
                class="ssss"
                >更多查询条件</el-link
              >
            </el-row>
          </el-form>
        </el-card>

        <el-card>
          <div class="text-right">
            <el-button
              size="mini"
              type="success"
              v-if="isShow && !showbtn"
              @click="generatingBills"
              >生成账单</el-button
            >
            <el-button
              size="mini"
              type="warning"
              v-if="showbtn"
              @click="updateSaleCustomerBill"
              >更新账单</el-button
            >

            <div style="float: left">
              <el-radio-group
                v-model="customerType"
                size="small"
                v-for="(item, k) in customerSon"
                :key="k"
              >
                <el-radio
                  :label="k"
                  @change="chooseQuery(k)"
                  border
                  style="margin-left: 10px"
                  >{{ customerSon[k] }}</el-radio
                >
              </el-radio-group>
            </div>
          </div>

          <el-table
            :row-key="rowKey"
            :data="columns"
            empty-text="请选择您的客户，查询相关费用"
            class=".el-table__body-wrapper"
            height="500"
            size="mini"
            ref="multipleTable"
          >
            <el-table-column
              type="selection"
              width="25"
              :reserve-selection="true"
            ></el-table-column>
            <el-table-column type="index" label="序号" width="35" />

            <el-table-column prop="serCusId" label="客户" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ customerSource[scope.row.serCusId] }}
              </template>
            </el-table-column>

            <el-table-column
              property="waybillNo"
              label="运单号"
              sortable
              width="78"
            />
            <el-table-column
              property="trackNumber"
              label="追踪号"
              show-overflow-tooltip
            />
            <el-table-column prop="costName" label="费用名称" width="70">
              <template slot-scope="scope">
                {{ costNameSource[scope.row.costName] }}
              </template>
            </el-table-column>

            <el-table-column
              property="unitPrice"
              width="50"
              label="单价"
              show-overflow-tooltip
            />

            <el-table-column
              property="count"
              label="数量"
              width="40"
              show-overflow-tooltip
            />

            <el-table-column
              property="currency"
              label="币种"
              sortable
              width="60"
            />

            <el-table-column
              width="58"
              property="totalCost"
              label="总额"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              property="remain"
              width="65"
              label="余额"
              sortable
              show-overflow-tooltip
            />

            <el-table-column
              property="accountDate"
              label="费用时间"
              sortable
              show-overflow-tooltip
              width="80"
            />

            <el-table-column
              property="arrivalPortTime"
              label="到港时间"
              show-overflow-tooltip
              sortable
              width="80"
            />
            <el-table-column
              property="leavePortTime"
              label="离港时间"
              show-overflow-tooltip
              sortable
              width="80"
            />

            <el-table-column
              property="signTime"
              label="签收时间"
              show-overflow-tooltip
              sortable
            />

            <el-table-column
              v-if="isShow"
              property="inStockTime"
              label="入库时间"
              show-overflow-tooltip
              sortable
            />

            <el-table-column
              v-if="billTypeShow"
              property="billType"
              label="账单类型"
            >
              <template slot-scope="scope">
                {{ billTypeSource[scope.row.billType] }}
              </template>
            </el-table-column>
            <el-table-column
              property="remark"
              label="备注"
              show-overflow-tooltip
            />

            <el-table-column width="100">
              <template slot="header" slot-scope="scope">
                <i
                  class="el-icon-plus margin-right-sm"
                  @click="editReceive()"
                  v-if="isShow"
                ></i>
              </template>
              <template slot-scope="scope">
                <i
                  v-if="isShow && scope.row.totalCost === scope.row.remain"
                  class="el-icon-plus margin-right-sm"
                  @click="editReceiveBySale(scope)"
                ></i>
                <i
                  v-if="isShow && scope.row.totalCost === scope.row.remain"
                  class="el-icon-edit"
                  @click="findBalanceDetail(scope)"
                ></i>
                <el-link
                  :underline="false"
                  icon="el-icon-minus"
                  v-if="showbtn"
                  @click="delData(scope)"
                ></el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :sm="5" :md="6" :lg="7" v-if="showHistorytable">
        <el-card>
          <span class="margin-right-sm">历史账单</span>
          <span v-if="showTitle"
            >(仅展示近20条，可在
            <span class="text-blue pointer" @click="toCustomerBill"
              >客户-账单列表</span
            >查询全部)</span
          >
          <el-table
            :data="historySaleCustomerBills"
            style="width: 100%"
            size="mini"
          >
            <el-table-column property="name" show-overflow-tooltip>
              <template slot-scope="scope">
                <div @click="viewDetail(scope)" class="pointer">
                  {{ scope.row.name }}
                </div>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot-scope="scope">
                <el-row>
                  <el-col :span="3">
                    <el-tooltip
                      content="全部销账"
                      placement="bottom-start"
                      effect="light"
                      v-if="list[scope.row.id] === 0"
                    >
                      <img :src="xiaogreenPng" />
                    </el-tooltip>
                    <el-tooltip
                      content="部分销账"
                      placement="bottom-start"
                      effect="light"
                      v-if="list[scope.row.id] < 0"
                    >
                      <img :src="xiaoyellowPng" />
                    </el-tooltip>
                    <el-tooltip
                      content="没有销账"
                      placement="bottom-start"
                      effect="light"
                      v-if="list[scope.row.id] !== 0 && list[scope.row.id] > 0"
                    >
                      <img :src="xiaogreyPng" />
                    </el-tooltip>
                  </el-col>
                  <el-col :span="21">
                    <el-row :gutter="8">
                      <el-col :span="4">
                        <el-tooltip
                          content="上传水单并转发"
                          placement="bottom-start"
                          effect="light"
                        >
                          <i
                            v-if="scope.row.status === -1"
                            class="el-icon-position margin-left-xs"
                            @click="toUploadBillImg(scope, 1)"
                            circle
                          ></i>
                        </el-tooltip>
                        <el-tooltip
                          content="上传水单"
                          placement="bottom-start"
                          effect="light"
                        >
                          <i
                            v-if="
                              scope.row.status !== 1 && scope.row.status !== -1
                            "
                            class="el-icon-upload2 margin-left-xs"
                            @click="toUploadBillImg(scope)"
                          ></i>
                        </el-tooltip>
                        <el-tooltip
                          content="查看水单"
                          placement="bottom-start"
                          effect="light"
                        >
                          <i
                            v-if="scope.row.status === 1"
                            class="el-icon-picture-outline margin-left-xs"
                            @click="lookUploadBillImg(scope)"
                          ></i>
                        </el-tooltip>
                      </el-col>
                      <el-col :span="4">
                        <el-tooltip
                          content="重命名"
                          placement="bottom-start"
                          effect="light"
                        >
                          <i
                            class="fa fa-wrench margin-left-xs"
                            @click="rename(scope)"
                          ></i>
                        </el-tooltip>
                      </el-col>
                      <el-col :span="4">
                        <el-tooltip
                          content="编辑"
                          placement="bottom-start"
                          effect="light"
                        >
                          <i
                            class="el-icon-edit margin-left-xs"
                            @click="editDetail(scope)"
                          ></i>
                        </el-tooltip>
                      </el-col>
                      <el-col :span="4">
                        <el-tooltip
                          content="导出excel账单"
                          placement="bottom-start"
                          effect="light"
                        >
                          <i
                            class="fa fa-file-excel margin-left-xs"
                            @click="selectExportTemplate(scope.row.id)"
                          ></i>
                        </el-tooltip>
                      </el-col>
                      <el-col :span="4">
                        <el-tooltip
                          content="导出pdf账单"
                          placement="bottom-start"
                          effect="light"
                        >
                          <i
                            class="fa fa-file-pdf margin-left-xs"
                            @click="selectExportTemplate(scope.row.id, 'PDF')"
                          ></i>
                        </el-tooltip>
                      </el-col>
                      <el-col :span="4">
                        <el-tooltip
                          content="删除账单"
                          placement="bottom-start"
                          effect="light"
                        >
                          <i
                            v-if="scope.row.status !== 1"
                            class="el-icon-delete margin-left-xs"
                            @click="deleteSaleCustomerBill(scope)"
                          />
                        </el-tooltip>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <!-- 新增编辑费用弹窗 -->
    <el-dialog title="编辑" :visible.sync="editReceiveDialog" width="40%">
      <el-form :model="receiveFrom" :rules="rules" ref="receiveFrom">
        <el-form-item label="运单号" label-width="200px" prop="waybillNo">
          <el-input
            v-model="receiveFrom.waybillNo"
            autocomplete="off"
            style="width: 300px"
            size="mini"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="公司" label-width="200px" prop="serCusId">
          <el-select
            style="width: 300px"
            v-model="receiveFrom.serCusId"
            filterable
            remote
            size="mini"
            reserve-keyword
            disabled
            clearable
            :remote-method="getCustomerMap"
            placeholder="请输入公司名称"
          >
            <el-option
              v-for="(item, value) in customerRemoteSource"
              :key="value"
              :label="item"
              :value="value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="费用名称" label-width="200px" prop="costName">
          <el-select
            v-model="receiveFrom.costName"
            placeholder="费用名称"
            style="width: 300px"
            size="mini"
            clearable
            filterable
          >
            <el-option
              v-for="(item, value) in costNameSource"
              :key="value"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数量" label-width="200px" prop="count">
          <el-input
            v-model="receiveFrom.count"
            autocomplete="off"
            style="width: 300px"
            size="mini"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="单价" label-width="200px" prop="unitPrice">
          <el-input
            v-model="receiveFrom.unitPrice"
            autocomplete="off"
            style="width: 300px"
            size="mini"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="币种" label-width="200px" prop="currency">
          <el-select
            v-model="receiveFrom.currency"
            placeholder="币种"
            style="width: 300px"
            size="mini"
            clearable
          >
            <el-option
              v-for="(item, value) in currencySource"
              :key="value"
              :label="item"
              :value="value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="账单类型" label-width="200px" prop="billType">
          <el-select
            v-model="receiveFrom.billType"
            placeholder="账单类型"
            style="width: 300px"
            size="mini"
            clearable
          >
            <el-option
              v-for="(item, value) in billTypeSource"
              :key="value"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="费用日期" label-width="200px" prop="accountDate">
          <el-date-picker
            placeholder="费用日期"
            suffix-icon="el-icon-date"
            v-model="receiveFrom.accountDate"
            value-format="yyyy-MM-dd"
            style="width: 300px"
            size="mini"
            clearable
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-form-item label="备注" label-width="200px" prop="remark">
            <el-input
              v-model="receiveFrom.remark"
              placeholder="备注"
              style="width: 300px"
              size="mini"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editReceiveDialogClose()"
          >取消</el-button
        >
        <el-button
          size="mini"
          type="primary"
          @click="saveSaleUpdateReceive('receiveFrom')"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 重命名 -->
    <el-dialog title="重命名" :visible.sync="renameDialog" width="40%">
      <el-form
        :model="formData"
        :rules="rules"
        label-width="80px"
        ref="formData"
        class="padding-lr-xl"
      >
        <el-form-item label="名称" prop="name">
          <el-input size="mini" v-model="formData.name" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="mini" type="primary" @click="submit('formData')"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 上传水单并转发弹窗 -->
    <el-dialog title="编辑" :visible.sync="toUpDialog">
      <el-form :model="toUpForm" label-width="150px" :rules="toUpRules">
        <el-form-item label="账单备注" prop="reamark">
          <el-input size="mini" v-model="toUpForm.remark" style="width: 80%" />
        </el-form-item>

        <div class="flex">
          <el-form-item label="账单总额">
            <span>{{ money }}</span>
          </el-form-item>
          <el-form-item label="账单余额">
            <span>{{ totalMoney }}</span>
          </el-form-item>
        </div>
        <el-form-item label="已有水单" v-if="isShowtwo">
          <span v-for="(v, i) in saleCustomerBillMemos" :key="i">
            <el-link
              type="primary"
              :underline="false"
              @click="imgOpen(v.memoImgUrl)"
              >水单{{ i + 1 }}
            </el-link>
            <i
              class="el-icon-close margin-right-sm"
              @click="deleteSaleCustomerBillMemo(v.id)"
            ></i>
          </span>
        </el-form-item>
        <el-row v-for="(item, index) in toUpForm.items" :key="index">
          <el-col :span="8">
            <el-form-item label="水单币种" prop="currency">
              <el-select
                v-model="item.currency"
                filterable
                clearable
                size="mini"
              >
                <el-option
                  v-for="(itm, idx) in currencyMap"
                  :key="idx"
                  :label="itm"
                  :value="itm"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="水单金额" prop="bankStatementAmount">
              <el-input
                size="mini"
                v-model="item.bankStatementAmount"
                style="width: 200px"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="水单" prop="memoImgUrl">
              <div class="flex">
                <el-input
                  size="mini"
                  style="width: 50%"
                  name="meno"
                  v-model="item.memoImgUrl"
                />

                <el-upload
                  class="flex"
                  action="#"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :http-request="uploadBillImg"
                  multiple
                  :limit="3"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                >
                  <el-button
                    size="small"
                    type="primary"
                    @click="selectTd(index)"
                    >点击上传</el-button
                  >
                </el-upload>
                <el-link
                  icon="el-icon-plus"
                  :underline="false"
                  class="margin-lr-xl"
                  @click="onAdd(item)"
                ></el-link>
                <el-link
                  icon="el-icon-minus"
                  :underline="false"
                  @click.prevent="removeDomain(item)"
                ></el-link>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="toUpDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="batchUploadBillImg"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog :title="lookUpTitle + ' 水单'" :visible.sync="lookUpDialog">
      <el-table :data="lookUpData" style="width: 100%" class="text-sm">
        <el-table-column
          label="水单金额"
          prop="bankStatementAmount"
        ></el-table-column>
        <el-table-column prop="currency" label="水单币种"> </el-table-column>
        <el-table-column label="图片" prop="memoImgUrl" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="imgUrl(scope)"
              >水单{{ scope.$index + 1 }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 导出弹窗 -->
    <el-dialog title="导出账单" :visible.sync="exportDialog" width="40%">
      <el-form :model="exportForm" :rules="rules" label-width="200px">
        <el-form-item label="文件" prop="fileTemplateId">
          <el-select
            size="mini"
            v-model="exportForm.fileTemplateId"
            style="width: 350px"
            clearable
            filterable
          >
            <el-option
              v-for="(v, i) in statementTemplates"
              :key="i"
              :label="v.fileName"
              :value="v.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="exportDialog = false">取消</el-button>
        <el-button size="mini" type="primary" @click="exportTemplate"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import { closeDialog } from "@/utils";
import axios from "axios";
import globalData from "@/utils/config";
import { untransform } from "@/store/yg/common/uri";
import * as constant from "@/store/yg/common/constant";
import xiaogreenPng from "@/assets/images/xiaogreen.png";
import xiaoyellowPng from "@/assets/images/xiaoyellow.png";
import xiaogreyPng from "@/assets/images/xiaogrey.png";
export default {
  props: ["field"],
  data() {
    return {
      currencyMap: {},
      currentPage: 1,
      pageSize: 500,
      totalSize: 0,
      indexFlag: true,
      list: {},
      xiaogreenPng: xiaogreenPng,
      xiaoyellowPng: xiaoyellowPng,
      xiaogreyPng: xiaogreyPng,
      fileUrl: constant.FILE_SERVER,
      // fileUrl: constant.FILE_SERVER,
      smWidth: 15,
      mdWidth: 16,
      lgWidth: 17,

      firstUploadImgUrl: null,
      customerSon: {},
      customerType: "",
      flag: true,
      showTitle: false,
      disCus: false,
      showHistorytable: true, //历史账单区域显示隐藏
      loading: false,
      exportDialog: false,
      renameDialog: false,
      toUpDialog: false,
      showHead: true,
      showHistory: false,
      lookUpDialog: false,
      editReceiveDialog: false,
      isShow: true,
      billListData: false,
      isShowtwo: false,
      showbtn: false,
      billTypeShow: false,
      selectTdIndex: "",
      lookUpTitle: "",
      titleName: "",
      formid: "",
      updateId: "",
      saveWaybillId: "",
      saveId: "",
      saleCustomerBillId: "",
      isFirst: "",
      fileId: "",
      fileType: "", //导出文件类型
      fileName: "", //导出文件名
      totalMoney: "", //水单账单余额
      money: "", //水单账单总额
      exportForm: {
        fileTemplateId: ""
      },
      formData: {
        name: ""
      },
      toUpForm: {
        remark: "",
        items: [{ bankStatementAmount: "", memoImgUrl: "", currency: "RMB" }]
      },
      headtotalCost: "", //头部应收总计
      headtotalRemain: "", //头部余额
      headAppend: "", //头部合计
      criteriaForm: {
        // 运单域查询
        waybillNoTextArea: "",
        waybillNos: [],
        referenceNoTextArea: "",
        referenceNos: [],
        trackNumbersTextArea: "",
        trackNumbers: [],
        countryId: "",
        costType: "0",
        shippingWays: [],
        shippingAddress: "",
        startArrivalPortDate: "",
        endArrivalPortDate: "",
        startLeavePortDate: "",
        endLeavePortDate: "",
        startSigneDate: "",
        endSigneDate: "",
        startInstockDate: "",
        endInstockDate: "",
        // 费用域查询
        customerId: "",
        currency: "",
        costName: "",
        startAccountDate: "",
        endAccountDate: ""
      },
      // 新增编辑费用
      receiveFrom: {
        id: "",
        waybillNo: "",
        waybillId: "",
        serCusId: "",
        saleId: "", //销售id
        saleCustomerBillId: "", //账单id(账单修改时存)
        billType: "",
        costName: "",
        count: "",
        unitPrice: "",
        currency: "",
        totalCost: "",
        remain: "",
        accountDate: "",
        remark: ""
      },
      toUpRules: {
        bankStatementAmount: [
          { required: true, message: "请输入水单金额", trigger: "blur" },
          {
            pattern: /(^[0-9.]{1,100}$)/,
            message: "水单金额不能包含特殊符号"
          }
        ]
      },
      //表单校验
      rules: {
        serCusId: [{ required: true, message: "请输入公司", trigger: "blur" }],
        name: [
          { required: true, message: "账单名称不能为空", trigger: "blur" },
          {
            pattern: /(^[\u4E00-\u9FA5a-zA-Z0-9-.（）()]{1,100}$)/,
            message: "账单名称不能包含特殊符号"
          }
        ],
        waybillNo: [
          { required: true, message: "请输入运单号", trigger: "blur" }
        ],
        costName: [
          { required: true, message: "请选择费用名称", trigger: "change" }
        ],
        unitPrice: [{ required: true, message: "请输入单价", trigger: "blur" }],
        count: [{ required: true, message: "请输入数量", trigger: "blur" }],
        currency: [
          { required: true, message: "请选择币种", trigger: "change" }
        ],
        billType: [
          { required: true, message: "请选择账单类型", trigger: "change" }
        ]
      },
      fileList: [],
      saleCustomerBillMemos: [], //水单集合
      lookUpData: [],
      cus: false,
      statementTemplates: [],
      historySaleCustomerBills: [], // 历史账单数据
      columns: [], //查询的表格数据
      customerSource: {}, // 客户
      customerRemoteSource: {}, //搜索的
      countrySource: {}, // 国家
      currencySource: {}, // 币种
      shippingWaySource: {}, // 物流方法
      shippingAddressSource: {}, // 起运地
      costNameSource: {}, // 费用名称
      billTypeSource: {}, // 账单类型
      tableData: [], //
      receiveId: [], //选中的应收id集合
      receiveId2: [],
      selectData: [],
      queryData: [], //存放查询出的数据
      tableColumns: [
        { prop: "waybillNo", label: "运单号" },
        { prop: "trackNumber", label: "追踪号" },
        { prop: "costName", label: "费用名称" },
        { prop: "unitPrice", label: "单价" },
        { prop: "count", label: "数量" },
        { prop: "currency", label: "币种" },
        { prop: "totalCost", label: "总额" },
        { prop: "remain", label: "余额" },
        { prop: "accountDate", label: "费用时间" },
        { prop: "arrivalPortTime", label: "到港时间" },
        { prop: "signTime", label: "签收时间" },
        { prop: "inStockTime", label: "入库时间", condition: "isShow" },
        { prop: "billType", label: "账单类型", condition: "billTypeShow" },
        { prop: "remark", label: "备注" }
      ]
    };
  },
  mounted() {
    this.init();
    this.tableListener();
    if (this.$route.query.id) {
      this.editBill();
    }
  },
  methods: {
    // 资源文件
    m(val) {
      return m(val);
    },
    rowKey(row) {
      return row.id;
    },
    findKey(obj, value, compare = (a, b) => a === b) {
      return Object.keys(obj).find(k => compare(obj[k], value));
    },
    tableListener() {
      let that = this;
      let dom = that.$refs.multipleTable.bodyWrapper;
      dom.addEventListener("scroll", function() {
        const scrollDistance =
          dom.scrollHeight - dom.scrollTop - dom.clientHeight;
        // console.log(scrollDistance);
        if (
          scrollDistance === 0 &&
          that.totalSize > 500 &&
          that.columns.length < that.totalSize
        ) {
          //scrollDistance 等于0证明已经到底，可以请求接口
          // that.currentPage++;
          that.requestData();
        }
      });
    },
    // 下拉加载更多数据
    async requestData() {
      // 获取表单数据
      let waybillQueryCriteria = this.criteriaForm;
      // 运单号
      let waybillNoTextArea = waybillQueryCriteria.waybillNoTextArea;
      waybillNoTextArea = waybillNoTextArea.replace(/(^\s*)|(\s*$)/g, "");
      if (waybillNoTextArea) {
        waybillQueryCriteria.waybillNos = waybillNoTextArea.split("\n");
        for (let i of waybillQueryCriteria.waybillNos) {
          i = i.replace(/(^\s*)|(\s*$)/g, "");
        }
      } else {
        waybillQueryCriteria.waybillNos = [];
      }
      waybillQueryCriteria.referenceNos;
      // 参考号
      let referenceNoTextArea = waybillQueryCriteria.referenceNoTextArea;
      if (referenceNoTextArea) {
        waybillQueryCriteria.referenceNos = referenceNoTextArea.split("\n");
      } else {
        waybillQueryCriteria.referenceNos = [];
      }
      // 追踪号
      let trackNumbersTextArea = waybillQueryCriteria.trackNumbersTextArea;
      if (trackNumbersTextArea) {
        waybillQueryCriteria.trackNumbers = trackNumbersTextArea.split("\n");
      } else {
        waybillQueryCriteria.trackNumbers = [];
      }
      // 客户
      if (!waybillQueryCriteria.customerId) {
        this.$message.error("请先选择客户");
        return;
      }
      // 分页参数
      this.currentPage++; // 页数+1
      waybillQueryCriteria.currentPage = this.currentPage;
      waybillQueryCriteria.pageSize = this.pageSize;

      this.loading = true;
      let res = await ajax("query", waybillQueryCriteria);
      if (res.success) {
        // 费用详情
        let waybillReceiveDetails = res.waybillReceiveDetails;
        this.customerSon = res.customerSon;
        console.log("子公司", this.customerSon);
        this.columns = this.columns.concat(waybillReceiveDetails);
        if (this.columns.length === res.totalSize) {
          this.$message.success(`已加载全部${res.totalSize}条`);
        } else {
          this.$message.success(
            `已加载${this.columns.length}条,剩余${res.totalSize -
              this.columns.length}条`
          );
        }
      } else {
        this.$message.error(m(res.message));
      }
      this.loading = false;
    },
    // 跳转到客户-账单列表
    toCustomerBill() {
      window.open(`#/main/customer__bill__list`);
    },
    // 页面初始化
    async init() {
      this.updateId = this.$route.query.id;
      let customerId = this.criteriaForm.customerId;
      this.isShow = true;
      let data = {};
      if (customerId) {
        var regex = /^[0-9]*$/;
        var regExp = new RegExp(regex);
        if (!regExp.test(customerId)) {
          this.$message.error("客户ID非法");
          return;
        }
        data["customerId"] = customerId;
      }
      let res = await ajax("init", data);
      // 显示当前销售的所有客户
      this.customerSource = res.customerSource;
      // 判断是否是客户信息页面跳转过来
      if (this.$route.query.customerId && this.$route.query.id === undefined) {
        this.cus = true;
        this.criteriaForm.customerId = parseInt(this.$route.query.customerId);
        this.query();
      }
      this.countrySource = res.countrySource;
      this.currencySource = res.currencySource;
      this.shippingWaySource = res.shippingWaySource;
      this.shippingAddressSource = res.shippingAddressSource;
      this.costNameSource = res.costNameSource;
      this.billTypeSource = res.billTypeSource; //账单类型
    },
    // 历史账单
    async history() {
      this.historySaleCustomerBills = [];
      this.list = []; // 图片渲染
      let waybillQueryCriteria = this.criteriaForm;
      this.showTitle = true;
      let res = await ajax("history", waybillQueryCriteria);
      console.log(res);
      if (res.saleCustomerBills) {
        let saleCustomerBills = res.saleCustomerBills; // 历史账单
        // 历史账单是否销账图标
        this.historySaleCustomerBills = saleCustomerBills;
        this.list = res.imageRender; // 图片渲染
      }
    },
    //根据条件搜索客户下拉
    async getCustomerMap(query) {
      let len = query.split(" ").join("").length;
      if (query !== "" && len > 0) {
        let map = await ajax("initCustomer", { customerNameShort: query });
        //console.log("map",map);
        this.customerRemoteSource = map;
      }
    },

    async chooseQuery(customerId) {
      // 获取表单数据
      console.log("当前customerId", customerId);
      let waybillQueryCriteria = {};
      waybillQueryCriteria.customerId = customerId;

      // 客户
      if (!waybillQueryCriteria.customerId) {
        this.$message.error("请先选择客户");
        return;
      }

      // //分页参数
      waybillQueryCriteria.currentPage = this.currentPage;
      waybillQueryCriteria.pageSize = this.pageSize;

      this.loading = true;
      waybillQueryCriteria.currentPage = 1;
      this.columns = [];
      let res = await ajax("query", waybillQueryCriteria);
      console.log(res);
      if (res.success) {
        // 费用详情
        let waybillReceiveDetails = res.waybillReceiveDetails;
        if (this.queryData.length !== 0) {
          this.columns = [...this.queryData, ...waybillReceiveDetails];
        } else {
          // this.columns = this.columns.concat(waybillReceiveDetails);
          this.columns = waybillReceiveDetails;
        }

        this.indexFlag = true;
        // 以下数据渲染在头部
        let totalCost = res.totalCost; // 应收总计
        this.headtotalCost = totalCost;
        let totalRemain = res.totalRemain; // 余额
        this.headtotalRemain = totalRemain;
        let append = res.append; // 合计数据
        this.headAppend = append;
        this.totalSize = res.totalSize;

        if (this.totalSize > 500 && this.columns.length !== this.totalSize) {
          this.$message.success(`已加载500条，剩余${this.totalSize - 500}条`);
        } else if (
          this.totalSize <= 500 &&
          this.columns.length !== this.totalSize &&
          this.totalSize !== 0
        ) {
          this.$message.success(`已加载全部${this.totalSize}条`);
        } else if (
          this.columns.length === this.totalSize &&
          this.totalSize !== 0
        ) {
          this.$message.success(`已加载全部${this.totalSize}条`);
        } else if (this.totalSize === 0) {
          this.$message.warning(`暂无数据`);
        }
      } else {
        this.$message.error(m(res.message));
      }
      this.loading = false;
      this.history();
    },

    // 查询按钮
    async query() {
      // 获取表单数据
      let waybillQueryCriteria = this.criteriaForm;
      // 运单号
      let waybillNoTextArea = waybillQueryCriteria.waybillNoTextArea;
      waybillNoTextArea = waybillNoTextArea.replace(/(^\s*)|(\s*$)/g, "");

      if (waybillNoTextArea) {
        waybillQueryCriteria.waybillNos = waybillNoTextArea.split("\n");
        for (let i of waybillQueryCriteria.waybillNos) {
          i = i.replace(/(^\s*)|(\s*$)/g, "");
        }
      } else {
        waybillQueryCriteria.waybillNos = [];
      }
      waybillQueryCriteria.referenceNos;
      // 参考号
      let referenceNoTextArea = waybillQueryCriteria.referenceNoTextArea;
      if (referenceNoTextArea) {
        waybillQueryCriteria.referenceNos = referenceNoTextArea.split("\n");
      } else {
        waybillQueryCriteria.referenceNos = [];
      }
      // 追踪号
      let trackNumbersTextArea = waybillQueryCriteria.trackNumbersTextArea;
      if (trackNumbersTextArea) {
        waybillQueryCriteria.trackNumbers = trackNumbersTextArea.split("\n");
      } else {
        waybillQueryCriteria.trackNumbers = [];
      }
      // 客户
      if (!waybillQueryCriteria.customerId) {
        this.$message.error("请先选择客户");
        return;
      }
      // if (this.indexFlag) {
      //   this.currentPage = 1;
      // }
      // //分页参数
      waybillQueryCriteria.currentPage = this.currentPage;
      waybillQueryCriteria.pageSize = this.pageSize;

      this.loading = true;
      waybillQueryCriteria.currentPage = 1;
      // 先清空查询前的表格数据
      this.columns = [];
      let res = await ajax("query", waybillQueryCriteria);
      if (res.success) {
        // 费用详情
        let waybillReceiveDetails = res.waybillReceiveDetails;
        // if (this.queryData.length !== 0) {
        //   this.columns = [...this.queryData, ...waybillReceiveDetails];
        // } else {
        // this.columns = this.columns.concat(waybillReceiveDetails);
        this.columns = waybillReceiveDetails;
        // }
        this.customerSon = res.customerSon;
        // console.log("子公司", this.customerSon);
        this.indexFlag = true;
        // 以下数据渲染在头部
        let totalCost = res.totalCost; // 应收总计
        this.headtotalCost = totalCost;
        let totalRemain = res.totalRemain; // 余额
        this.headtotalRemain = totalRemain;
        let append = res.append; // 合计数据
        this.headAppend = append;
        this.totalSize = res.totalSize;
        // this.queryData = res.waybillReceiveDetails;
        this.queryData = [...this.queryData, ...res.waybillReceiveDetails];
        if (this.totalSize > 500 && this.columns.length !== this.totalSize) {
          this.$message.success(`已加载500条，剩余${this.totalSize - 500}条`);
        } else if (
          this.totalSize <= 500 &&
          this.columns.length !== this.totalSize &&
          this.totalSize !== 0
        ) {
          this.$message.success(`已加载全部${this.totalSize}条`);
        } else if (
          this.columns.length === this.totalSize &&
          this.totalSize !== 0
        ) {
          this.$message.success(`已加载全部${this.totalSize}条`);
        } else if (this.totalSize === 0) {
          this.$message.warning(`暂无数据`);
        }
      } else {
        this.$message.error(m(res.message));
      }
      this.loading = false;
      this.history();
    },
    onAdd(item) {
      if (item.bankStatementAmount) {
        this.toUpForm.items.push({ bankStatementAmount: "", memoImgUrl: "" });
      } else {
        this.$message.error("请先填写当前水单金额再新增");
      }
    },
    removeDomain(k) {
      var index = this.toUpForm.items.indexOf(k);
      if (index !== -1) {
        this.toUpForm.items.splice(index, 1);
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    imgOpen(memoImgUrl) {
      window.open(this.fileUrl + memoImgUrl);
    },
    // 操作上传水单保存水单
    async batchUploadBillImg() {
      let memoArray = [];
      for (let i = 0; i < this.toUpForm.items.length; i++) {
        if (!this.toUpForm.items[i].bankStatementAmount) {
          this.$message.error(`请检查第${i + 1}个水单，金额没有填写`);
          return false;
        } else if (!this.toUpForm.items[i].memoImgUrl) {
          this.$message.error(`请检查第${i + 1}个水单，文件没有上传`);
          return false;
        }
        let obj = {};
        obj["bankStatementAmount"] = this.toUpForm.items[i].bankStatementAmount;
        obj["memoImgUrl"] = this.toUpForm.items[i].memoImgUrl;
        obj["currency"] = this.toUpForm.items[i].currency;
        memoArray.push(obj);
        if (null == this.firstUploadImgUrl) {
          this.firstUploadImgUrl = this.toUpForm.items[i].memoImgUrl;
        }
      }
      if (this.isFirst == 1 && memoArray.length == 0) {
        this.$message.error("请先上传水单");
        return;
      }
      let res = await ajax("batchUploadBillImg", {
        saleCustomerBillId: this.fileId,
        isFirst: this.isFirst,
        remark: this.toUpForm.remark,
        memoArray: memoArray
      });
      console.log(res);
      if (res.success) {
        this.$message.success("上传成功");
        this.history();
      } else {
        this.$message.error(m(res.message));
      }
      this.toUpDialog = false;
    },
    // 操作上传水单弹窗上传文件
    uploadBillImg(params, i) {
      const formData = new FormData();
      formData.append("items[]", params.file);
      const action =
        constant.API_SERVER +
        "/api/consume/upload?uri=/customer/bill/list" +
        "&f=uploadBillImg&type=main";
      axios({
        url: action,
        method: "post",
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }).then(res => {
        console.log("res :>> ", res);
        console.log(res.data.data.fileUrl);
        if (res.data.code === 200) {
          this.toUpForm.items[this.selectTdIndex].memoImgUrl =
            res.data.data.fileUrl;
        } else {
          this.$message.error(res.data.data.message);
        }
      });
    },
    selectTd(index) {
      this.selectTdIndex = index;
    },
    // 操作上传水单
    async toUploadBillImg(scope, isFirst) {
      this.toUpForm.items = [{}];
      this.fileList = [];
      this.isShowtwo = false;
      this.saleCustomerBillMemos = [];
      this.fileId = scope.row.id;
      let res = await ajax("toUploadBillImg", {
        id: scope.row.id,
        isFirst: isFirst
      });
      console.log(res);
      this.toUpDialog = true;
      if (
        res.saleCustomerBillMemos !== undefined &&
        res.saleCustomerBillMemos.length > 0
      ) {
        this.isShowtwo = true;
        this.saleCustomerBillMemos = res.saleCustomerBillMemos;
      }
      this.totalMoney = res.totalCost;
      this.money = res.totalRemain;
      this.toUpForm.remark = res.saleCustomerBill.remark;
      this.isFirst = res.isFirst;

      const attrs = {
        class: "com.tofba.app.client.customer.CustomerBalanceDetailClient"
      };
      let initRes = await ajax("init", {}, attrs);
      console.log(initRes);
      if (!initRes) {
        this.$message.error("初始化页面信息失败，请刷新重试");
        return;
      }
      this.currencyMap = initRes.currencySource;
    },
    // 删除水单后重新请求数据
    async toupload() {
      let res = await ajax("toUploadBillImg", {
        id: this.fileId
      });
      if (
        res.saleCustomerBillMemos !== undefined &&
        res.saleCustomerBillMemos.length !== 0
      ) {
        this.isShowtwo = true;
        this.saleCustomerBillMemos = res.saleCustomerBillMemos;
      } else {
        this.isShowtwo = false;
      }
      this.totalMoney = res.totalRemain;
      this.money = res.totalCost;
      this.toUpForm.remark = res.saleCustomerBill.remark;
      this.isFirst = res.isFirst;
    },
    // 删除水单
    async deleteSaleCustomerBillMemo(id) {
      let res = await ajax("deleteSaleCustomerBillMemo", { id: id });
      console.log(res);
      if (res.code === 200) {
        this.$message.success("删除成功");
        this.toupload();
      } else {
        this.$message.error(m(res.message));
      }
    },

    // 新增编辑费用
    async editReceive(id, waybillId) {
      let params = {};
      let customerId = this.criteriaForm.customerId;
      if (!customerId) {
        // this.$message.error("请先选择客户");
        // return;
      }
      params["customerId"] = customerId;
      if (id) {
        // 应收应付ID
        params["id"] = id;
      } else {
        this.saveId = null;
      }
      if (waybillId) {
        // 运单ID
        params["waybillId"] = waybillId;
      }
      console.log(JSON.stringify(params));
      let res = await ajax("editReceive", params);
      let success = res.success;
      if (!success) {
        let message = res.message;
        this.$message.error(m(message));
        return;
      }
      // 响应成功
      // 当ID不为空时才返回
      this.editReceiveDialog = true;
      let receivable = res.receivable; //应收信息
      // 当前端waybillId不为空时才有此两项返回
      let waybillNo = res.waybillNo; //订单号
      if (waybillNo) {
        this.receiveFrom.waybillNo = waybillNo;
      }
      let _waybillId = res.waybillId; //订单ID
      if (_waybillId) {
        this.receiveFrom.waybillId = _waybillId;
      }
      // 客户ID不为空时返回
      let customerName = res.customerName; //客户简称
      let _customerId = res.customerId; //客户ID
      if (_customerId) {
        this.receiveFrom.serCusId = this.customerSource[_customerId];
        this.receiveFrom.costName = "";
        this.receiveFrom.waybillNo = "";
        this.receiveFrom.count = "";
        this.receiveFrom.unitPrice = "";
        this.receiveFrom.currency = "";
        this.receiveFrom.billType = "";
        this.receiveFrom.accountDate = "";
        this.receiveFrom.remark = "";
      }
      // 响应成功返回
      let currencySource = res.currencySource; //币种
      this.currencySource = currencySource;
      let costNameSource = res.costNameSource; //费用名称
      this.costNameSource = costNameSource;
      let billTypeSource = res.billTypeSource; // 账单类型
      this.billTypeSource = billTypeSource;
    },
    async editReceiveBySale(scope) {
      let res = await ajax("editReceive", {
        customerId: this.criteriaForm.customerId,
        waybillId: scope.row.waybillId,
        id: scope.row.id
      });
      this.saveId = null;
      console.log(res);
      if (res.success) {
        this.editReceiveDialog = true;
        this.receiveFrom.waybillNo = res.waybillNo;
        this.receiveFrom.waybillId = res.waybillId;
        this.receiveFrom.serCusId = res.customerName;
        this.receiveFrom.costName = "";
        this.receiveFrom.count = "";
        this.receiveFrom.unitPrice = "";
        this.receiveFrom.currency = "";
        this.receiveFrom.billType = "";
        this.receiveFrom.accountDate = "";
        this.receiveFrom.remark = "";
      }
    },
    // 弹窗隐藏
    editReceiveDialogClose() {
      this.editReceiveDialog = false;
    },
    // 保存费用
    async saveSaleUpdateReceive(formName) {
      console.log(formName);
      this.$refs[formName].validate(valid => {
        if (valid) {
          return;
        }
      });
      let serCusId = this.criteriaForm.customerId;
      let costName = this.findKey(
        this.costNameSource,
        this.receiveFrom.costName
      );
      let billType = this.findKey(
        this.billTypeSource,
        this.receiveFrom.billType
      );
      let res = await ajax("saveSaleUpdateReceive", {
        id: this.saveId,
        waybillId: this.receiveFrom.waybillId,
        waybillNo: this.receiveFrom.waybillNo,
        serCusId: serCusId,
        costName: costName,
        unitPrice: this.receiveFrom.unitPrice,
        count: this.receiveFrom.count,
        currency: this.receiveFrom.currency,
        billType: billType,
        accountDate: this.receiveFrom.accountDate,
        remark: this.receiveFrom.remark
      });
      console.log(res);
      if (res.success) {
        this.$message.success("操作成功");
        this.editReceiveDialog = false;
        //this.query();
        //this.reload();
        if (!this.showbtn) {
          this.query();
        } else if (res.id != null) {
          console.log("1111111111111111111111");
          this.queryData.push({
            id: res.id,
            waybillId: this.receiveFrom.waybillId,
            waybillNo: this.receiveFrom.waybillNo,
            serCusId: serCusId,
            costName: costName,
            unitPrice: this.receiveFrom.unitPrice,
            count: this.receiveFrom.count,
            totalCost: this.receiveFrom.totalCost,
            remain: this.receiveFrom.remain,
            currency: this.receiveFrom.currency,
            billType: billType,
            accountDate: this.receiveFrom.accountDate,
            remark: this.receiveFrom.remark
          });
          //this.$refs.multipleTable.clearSelection();
          //this.toggleSelection();
          this.$refs.multipleTable.selection.push({
            id: res.id
          });
          this.updateSaleCustomerBill();
        } else {
          this.updateSaleCustomerBill();
        }
      } else {
        this.$message.error(m(`${res.message}`));
      }
    },
    changeData() {
      this.flag = !this.flag;
    },
    async findBalanceDetail(scope) {
      this.saveId = scope.row.id;
      let res = await ajax("editReceive", {
        customerId: this.criteriaForm.customerId,
        waybillId: this.receiveFrom.waybillId,
        id: scope.row.id
      });
      console.log(res);
      if (res.success) {
        this.editReceiveDialog = true;
        this.receiveFrom = res.receivable;
        this.receiveFrom.waybillNo = res.waybillNo;
        this.receiveFrom.serCusId = res.customerName;
        this.receiveFrom.costName = this.costNameSource[
          res.receivable.costName
        ];
        this.receiveFrom.billType = this.billTypeSource[
          res.receivable.billType
        ];
      } else {
        this.$message.error(m(`${res.message}`));
      }
    },
    toggleSelection() {
      this.$nextTick(() => {
        this.$refs.multipleTable.toggleAllSelection(); // 全选
      });
    },
    //批量生成账单
    async generatingBills() {
      this.receiveId2 = [];
      this.selectData = [];
      this.selectData = this.$refs.multipleTable.selection;
      for (let i in this.selectData) {
        this.receiveId2.push(this.selectData[i].id);
      }
      let customerId = this.criteriaForm.customerId;
      let costType2 = this.criteriaForm.costType;
      console.log("账单客户名", this.customerSource[customerId]);
      this.customerSource[customerId] = this.customerSource[customerId].replace(
        /\s*/g,
        ""
      );
      let billName = `${this.customerSource[customerId]}-${this.criteriaForm.startAccountDate}-${this.criteriaForm.endAccountDate}账单`;
      if (
        this.criteriaForm.startAccountDate === "" ||
        this.criteriaForm.endAccountDate === ""
      ) {
        return this.$message.error("请先录入费用时间,查询后再生成账单");
      } else if (this.receiveId2.length === 0) {
        return this.$message.error("请先选择费用,再生成账单");
      }
      let attrs = {};
      attrs["headers"] = {
        "YG-UNIQUE-KEY": "createSaleCustomerBill" + new Date().getTime()
      };
      let res = await ajax(
        "createSaleCustomerBill",
        {
          customerId: customerId,
          billName: billName,
          receiveId: this.receiveId2,
          costType: costType2
        },
        attrs
      );
      console.log(res);
      if (res.success) {
        this.$message.success("生成账单成功");
        this.query();
        this.criteriaForm.startAccountDate = "";
        this.criteriaForm.endAccountDate = "";
        // 先清除上次选中的状态
        this.$refs.multipleTable.clearSelection();
      } else {
        this.$message.error(m(res.message));
      }
    },
    // 历史账单编辑-删除
    delData(scope) {
      let index = scope.$index;
      this.columns.splice(index, 1);
      // 先清除上次选中的状态
      this.$refs.multipleTable.clearSelection();
      // 选中所有数据
      this.toggleSelection();
      // console.log(this.$refs.multipleTable.selection);
    },
    // 更新账单按钮
    async updateSaleCustomerBill() {
      this.receiveId2 = [];
      this.selectData = [];
      //console.log(this.$refs.multipleTable.selection);
      console.log(this.queryData);
      // if (
      //   this.billListData &&
      //   this.$refs.multipleTable.selection.length < this.queryData.length
      // ) {
      //   this.selectData = this.queryData;
      // } else {
      //   this.selectData = this.$refs.multipleTable.selection;
      // }
      this.selectData = this.$refs.multipleTable.selection;
      for (let i in this.selectData) {
        this.receiveId2.push(this.selectData[i].id);
      }
      let res = await ajax("updateSaleCustomerBill", {
        id: this.updateId,
        receiveId: this.receiveId2
      });
      console.log(res);
      if (res.success) {
        this.$message.success("更新账单成功");
        this.editSaleCustomerBillDetail();
        this.toggleSelection();
      } else {
        this.$message.error(m(`${res.message}`));
      }
    },
    // 更新账单后请求数据
    async editSaleCustomerBillDetail() {
      let res = await ajax("editDetail", {
        id: this.updateId
      });
      console.log(res);
      if (res.success) {
        this.isShow = true;
        this.billTypeShow = true;
        this.showbtn = true;
        this.showHead = false;
        this.showHistory = true;
        this.titleName = res.saleCustomerBill.name;
        this.headtotalCost = res.totalCost;
        let append = res.append; // 合计数据
        this.headAppend = append;
        this.headtotalRemain = res.totalRemain;
        this.columns = res.waybillReceiveDetails;
        this.queryData = res.waybillReceiveDetails;
        this.toggleSelection();
      } else {
        this.$message.error(m(res.message));
      }
    },
    // 账单列表跳转的编辑
    async editBill() {
      console.log(this.$refs.multipleTable.selection);
      this.showHistorytable = false;
      this.disCus = true; //禁止修改客户公司
      this.smWidth = 24;
      this.mdWidth = 24;
      this.lgWidth = 24;
      let id = this.$route.query.id;
      this.cus = true;
      this.criteriaForm.customerId = parseInt(this.$route.query.customerId);
      let res = await ajax("editDetail", {
        id: id
      });
      console.log(res);
      if (res.success) {
        this.isShow = true;
        this.billListData = true;
        this.billTypeShow = true;
        this.showbtn = true;
        this.showHead = false;
        this.showHistory = true;
        let append = res.append; // 合计数据
        this.headAppend = append;
        this.titleName = res.saleCustomerBill.name;
        this.headtotalCost = res.totalCost;
        this.headtotalRemain = res.totalRemain;
        this.columns = res.waybillReceiveDetails;
        this.queryData = res.waybillReceiveDetails;
        // this.toggleSelection();
      } else {
        this.$message.error(m(res.message));
      }
      console.log(this.queryData);
    },
    // 导出选择模板
    async selectExportTemplate(id, fileType) {
      this.saleCustomerBillId = id;
      let res = await ajax("selectExportTemplate", {
        saleCustomerBillId: id,
        fileType: fileType
      });
      console.log(res);
      if (res.success) {
        this.statementTemplates = res.statementTemplates;
        this.fileType = res.fileType;
        this.fileName = res.fileName;
        this.exportDialog = true;
        this.exportForm.fileTemplateId = "";
      } else {
        this.$message.error(m(res.message));
      }
    },
    // 导出账单
    async exportTemplate() {
      let param = {};
      param["saleCustomerBillId"] = this.saleCustomerBillId;
      param["fileTemplateId"] = this.exportForm.fileTemplateId;
      param["fileType"] = this.fileType;
      param["fileName"] = this.fileName;
      let res = await ajax("exportTemplate", param);
      console.log(res);
      if (res.success) {
        window.open(constant.FILE_SERVER + res.filePath);
        this.exportDialog = false;
      } else {
        this.$message.error("导出失败");
      }
    },
    // 查看水单
    async lookUploadBillImg(scope) {
      this.lookUpDialog = true;
      this.lookUpTitle = scope.row.name;
      let id = scope.row.id;
      let res = await ajax("viewBillMemo", {
        id: id
      });
      console.log(res);
      this.lookUpData = res.billmemos;
    },
    // 水单图片url
    imgUrl(scope) {
      window.open(this.fileUrl + scope.row.memoImgUrl);
    },
    // 账单历史详情删除操作
    deleteSaleCustomerBill(scope) {
      let id = scope.row.id;
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          ajax("deleteSaleCustomerBillById", { id: id }).then(
            res => {
              console.log(res);
              if (res.code !== 200) {
                this.$message.error(m(res.message));
              } else {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });

                // this.columns = res.data;
                this.history();
                this.columns = [];
                // this.isShow = false;
                this.showbtn = false;
                // this.billTypeShow = true;
                this.showHead = false;
                this.showHistory = true;
                this.headtotalCost = false;
                this.headtotalRemain = false;
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 重置
    reset() {
      // this.criteriaForm = {};
      // this.columns = [];
      // this.historySaleCustomerBills = [];
      // this.showHistory = false;
      // this.showbtn = false;
      // this.billTypeShow = false;
      // this.isShow = true;
      // this.disCus = false; //禁止修改客户公司
      location.reload();
    },
    // 点击历史账单查看详情
    async viewDetail(scope) {
      let id = scope.row.id;
      let res = await ajax("viewDetail", {
        id: id
      });
      console.log(res);
      // this.isShow = false;
      this.showbtn = false;
      this.billTypeShow = true;
      this.showHead = false;
      this.showHistory = true;
      this.headtotalCost = res.totalCost;
      this.headtotalRemain = res.totalRemain;
      this.titleName = res.saleCustomerBill.name;
      this.columns = res["waybillReceiveDetails "];
    },
    // 点击历史账单编辑
    async editDetail(scope) {
      if (this.list[scope.row.id] === 0) {
        return this.$message.error("已销账,不允许再编辑");
      }
      let id = scope.row.id;
      this.updateId = scope.row.id;
      this.receiveId = scope.row.saleCustomerBillReceives;
      let res = await ajax("editDetail", {
        id: id
      });
      console.log(res);
      if (res.success) {
        this.isShow = true;
        this.billTypeShow = true;
        this.showbtn = true;
        this.showHead = false;
        this.showHistory = true;
        this.disCus = true; //禁止修改客户公司
        this.titleName = res.saleCustomerBill.name;
        this.headtotalCost = res.totalCost;
        let append = res.append; // 合计数据
        this.headAppend = append;
        this.headtotalRemain = res.totalRemain;
        this.columns = res.waybillReceiveDetails;
        this.queryData = res.waybillReceiveDetails;
        // 先清除上次选中的状态
        this.$refs.multipleTable.clearSelection();
        // 选中所有数据
        this.toggleSelection();
      } else {
        this.$message.error(m(res.message));
      }
    },
    // 点击弹出重命名对话框
    rename(scope) {
      this.renameDialog = true;
      this.formData.name = scope.row.name;
      this.formid = scope.row.id;
    },
    submit(value) {
      this.$refs[value].validate(valid => {
        if (valid) {
          this.renameBill();
        } else {
          return false;
        }
      });
    },
    //账单重命名
    async renameBill() {
      // if (this.formData.name === "") {
      //   return this.$message.error("名称不能为空");
      // }
      let res = await ajax("renameBill", {
        id: this.formid,
        name: this.formData.name
      });
      console.log(res);
      if (res.code === 200) {
        this.$message.success("修改成功");
        this.history();
        this.renameDialog = false;
      } else {
        this.$message.error(m(res.message));
      }
    }
  }
};
</script>

<style scoped>
.maxheight {
  display: none;
}

.transition-box {
  margin-bottom: 10px;
  width: 200px;
  height: 100px;
  border-radius: 4px;
  background-color: #409eff;
  text-align: center;
  color: #fff;
  padding: 40px 20px;
  box-sizing: border-box;
  margin-right: 20px;
}
/deep/ .el-card {
  margin-top: 10px;
  margin-bottom: 20px;
  margin-left: 10px;
  margin-right: 10px;
}
.margin_bottom {
  margin-bottom: -20px;
}
.headDiv {
  position: fixed;
  top: 20px;
  z-index: 1001;
}
/deep/ .el-table th.gutter {
  display: table-cell !important;
}

/deep/ .el-table .cell {
  padding: 0;
}

/deep/ .el-table th.gutter {
  display: table-cell !important;
}
</style>
